package com.bms.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Node;

/**
 * @author Lan
 */
public class XmlUtil {
	
	protected static Logger logger = Logger.getLogger(XmlUtil.class);
	
	/**
	 * 将org.w3c.dom类型的xml转换成字符串
	 * @author Lan
	 * @param node
	 * @return
	 */
	public static String xmlToString(Node node) {
		String xmlStr = "";
		try {
			Source source = new DOMSource(node);
			StringWriter stringWriter = new StringWriter();
			Result result = new StreamResult(stringWriter);
			
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.transform(source, result);
			xmlStr = stringWriter.getBuffer().toString();
		} catch (TransformerConfigurationException e) {
			logger.error("TransformerFactory实例化异常", e);
		} catch (TransformerException e) {
			logger.error("Xml对象转化成String字符串时出现异常", e);
		} 
		return xmlStr;
	}

	/**
	 * 保存xml文档(utf-8)到本地
	 * 
	 * @author Lan
	 * @param document
	 * @param savePath
	 *            保存的全路径（路径+文件名）
	 */
	public static boolean outXmlLocal(Document document, String savePath) {
		return outXmlLocal(document, savePath, "UTF-8");
	}
	
	/**
	 * 保存xml文档到本地
	 * @param document
	 * @param savePath
	 * @param encoding
	 * @return
	 * @author Lan
	 */
	public static boolean outXmlLocal(Document document, String savePath, String encoding) {
		boolean isSucc = false;
		try {
			if(document != null){
				if(FileUtil.createDir(savePath)){
					OutputFormat format = OutputFormat.createPrettyPrint();
					if(StringUtils.isBlank(encoding))
						encoding = "UTF-8";
					format.setEncoding(encoding);
					
					XMLWriter writer = new XMLWriter(new FileOutputStream(new File(savePath)), format);
					writer.write(document);
					writer.close();
					
					isSucc = true;
					logger.debug("Xml的保存路径：" + savePath);
				}
			} else {
				logger.error("需要保存的documnet为空");
			}
		} catch (Exception e) {
			logger.error("保存xml文件失败", e);
		}
		return isSucc;
	}
	/**
	 * 读取本地xml文件
	 * @author Lan
	 * @param file
	 * @return
	 */
	public static Document getXmlDocument(File file){
		Document document = null;
		SAXReader reader = new SAXReader();
		try {
			if(file != null && file.isFile())
				document = reader.read(file);
		} catch (DocumentException e) {
			logger.error("读取XML文件错误", e);
		}
		return document;
	}
}
